// 个人中心JavaScript

let userData = {};
let quizHistory = [];

// 配置marked选项
if (typeof marked !== 'undefined') {
    marked.setOptions({
        breaks: true,
        gfm: true,
        sanitize: false
    });
}

// Markdown渲染辅助函数
function renderMarkdown(text) {
    if (!text) return '';
    if (typeof marked !== 'undefined') {
        return marked.parse(text);
    }
    return text;
}

// 渲染数学公式
function renderMath(element) {
    if (typeof window.renderMathInElement !== 'undefined' && typeof katex !== 'undefined') {
        try {
            window.renderMathInElement(element, {
                delimiters: [
                    {left: '$$', right: '$$', display: true},
                    {left: '$', right: '$', display: false},
                    {left: '\\[', right: '\\]', display: true},
                    {left: '\\(', right: '\\)', display: false}
                ],
                throwOnError: false
            });
        } catch (e) {
            console.warn('数学公式渲染失败:', e);
        }
    }
}

// 头像上传功能
function setupAvatarUpload() {
    const avatarInput = document.getElementById('avatarInput');
    const avatarPreview = document.getElementById('avatarPreview');
    const avatarPreviewPlaceholder = document.getElementById('avatarPreviewPlaceholder');
    const uploadAvatarForm = document.getElementById('uploadAvatarForm');
    const avatarError = document.getElementById('avatarError');

    if (!avatarInput || !uploadAvatarForm) return;

    // 预览头像
    avatarInput.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            // 检查文件大小 (5MB)
            if (file.size > 5 * 1024 * 1024) {
                avatarError.textContent = '文件大小不能超过5MB';
                return;
            }
            
            // 检查文件类型
            const allowedTypes = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/webp'];
            if (!allowedTypes.includes(file.type)) {
                avatarError.textContent = '只支持 PNG、JPG、GIF、WEBP 格式';
                return;
            }
            
            // 预览图片
            const reader = new FileReader();
            reader.onload = function(event) {
                if (avatarPreview) {
                    avatarPreview.src = event.target.result;
                    avatarPreview.style.display = 'block';
                }
                if (avatarPreviewPlaceholder) {
                    avatarPreviewPlaceholder.style.display = 'none';
                }
            };
            reader.readAsDataURL(file);
            avatarError.textContent = '';
        }
    });

    // 上传头像
    uploadAvatarForm.addEventListener('submit', async function(e) {
        e.preventDefault();
        
        const file = avatarInput.files[0];
        if (!file) {
            avatarError.textContent = '请选择头像图片';
            return;
        }
        
        const formData = new FormData();
        formData.append('avatar', file);
        
        const uploadBtn = document.getElementById('uploadAvatarBtn');
        uploadBtn.disabled = true;
        uploadBtn.textContent = '上传中...';
        
        try {
            const response = await fetch('/api/user/upload-avatar', {
                method: 'POST',
                body: formData
            });
            
            const data = await response.json();
            
            if (data.success) {
                alert('头像上传成功！');
                // 更新页面上的头像
                const userAvatar = document.getElementById('userAvatar');
                const avatarPlaceholder = document.getElementById('avatarPlaceholder');
                const avatarPreview = document.getElementById('avatarPreview');
                const avatarPreviewPlaceholder = document.getElementById('avatarPreviewPlaceholder');
                
                // 添加时间戳防止浏览器缓存
                const avatarUrlWithTimestamp = data.avatar_url + '?t=' + new Date().getTime();
                
                if (userAvatar) {
                    userAvatar.src = avatarUrlWithTimestamp;
                    userAvatar.style.display = 'block';
                }
                if (avatarPlaceholder) {
                    avatarPlaceholder.style.display = 'none';
                }
                // 同时更新头像预览
                if (avatarPreview) {
                    avatarPreview.src = avatarUrlWithTimestamp;
                    avatarPreview.style.display = 'block';
                }
                if (avatarPreviewPlaceholder) {
                    avatarPreviewPlaceholder.style.display = 'none';
                }
                avatarError.textContent = '';
            } else {
                avatarError.textContent = data.message || '上传失败';
            }
        } catch (error) {
            console.error('上传头像错误:', error);
            avatarError.textContent = '上传失败，请重试';
        } finally {
            uploadBtn.disabled = false;
            uploadBtn.textContent = '上传头像';
        }
    });
}

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    console.log('个人中心页面已加载');
    
    // 检查登录状态
    checkAuthStatus();
    
    // 初始化
    setupTabs();
    setupForms();
    setupLogout();
    setupDetailModal();
    setupAvatarUpload(); // 初始化头像上传
    
    // 加载数据
    loadUserProfile();
    loadQuizHistory();
});

// 检查登录状态
function checkAuthStatus() {
    fetch('/api/check-auth')
        .then(response => response.json())
        .then(data => {
            if (!data.logged_in) {
                // 未登录，跳转到登录页
                window.location.href = '/login';
            } else {
                // 已登录，更新用户名显示
                if (data.username) {
                    document.getElementById('usernameDisplay').textContent = data.username;
                }
            }
        })
        .catch(error => {
            console.error('检查登录状态失败:', error);
            window.location.href = '/login';
        });
}

// 设置标签页
function setupTabs() {
    const tabButtons = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content');
    
    tabButtons.forEach(btn => {
        btn.addEventListener('click', function() {
            const targetTab = this.getAttribute('data-tab');
            
            // 更新按钮状态
            tabButtons.forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            
            // 更新内容显示
            tabContents.forEach(content => {
                content.classList.remove('active');
                const tabId = content.id.replace('Tab', '');
                if (tabId === targetTab) {
                    content.classList.add('active');
                }
            });
        });
    });
}

// 设置表单
function setupForms() {
    // 修改信息表单
    document.getElementById('updateInfoForm').addEventListener('submit', function(e) {
        e.preventDefault();
        updateUserInfo();
    });
    
    // 修改密码表单
    document.getElementById('updatePasswordForm').addEventListener('submit', function(e) {
        e.preventDefault();
        updatePassword();
    });
}

// 设置登出
function setupLogout() {
    document.getElementById('logoutBtn').addEventListener('click', function() {
        if (confirm('确定要退出登录吗？')) {
            fetch('/api/logout', {
                method: 'POST'
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    window.location.href = '/';
                }
            })
            .catch(error => {
                console.error('登出失败:', error);
                window.location.href = '/';
            });
        }
    });
}

// 加载用户资料
function loadUserProfile() {
    // 这里可以使用用户ID从session获取信息
    fetch('/api/user/profile')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                userData = data.user;
                displayUserInfo(data.user);
            }
        })
        .catch(error => {
            console.error('加载用户资料失败:', error);
        });
}

// 显示用户信息
function displayUserInfo(user) {
    document.getElementById('usernameDisplay').textContent = user.username;
    document.getElementById('userEmail').textContent = user.email;
    document.getElementById('quizCount').textContent = user.quiz_count || 0;
    document.getElementById('totalScore').textContent = user.score || 0;
    
    // 显示头像
    if (user.avatar) {
        const userAvatar = document.getElementById('userAvatar');
        const avatarPlaceholder = document.getElementById('avatarPlaceholder');
        const avatarPreview = document.getElementById('avatarPreview');
        
        if (userAvatar) {
            userAvatar.src = user.avatar;
            userAvatar.style.display = 'block';
        }
        if (avatarPlaceholder) {
            avatarPlaceholder.style.display = 'none';
        }
        if (avatarPreview) {
            avatarPreview.src = user.avatar;
            avatarPreview.style.display = 'block';
            const previewPlaceholder = document.getElementById('avatarPreviewPlaceholder');
            if (previewPlaceholder) previewPlaceholder.style.display = 'none';
        }
    }
    
    // 计算平均得分
    const avgScore = user.quiz_count > 0 ? Math.round(user.score / user.quiz_count) : 0;
    document.getElementById('avgScore').textContent = avgScore;
    
    // 显示注册时间
    if (user.created_at) {
        const date = new Date(user.created_at);
        document.getElementById('joinDate').textContent = 
            date.toLocaleDateString('zh-CN');
    }
    
    // 设置表单默认值
    document.getElementById('updateUsername').value = user.username;
    document.getElementById('updateEmail').value = user.email;
}

// 加载答题记录
function loadQuizHistory() {
    fetch('/api/user/quiz-history')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                quizHistory = data.history || [];
                displayQuizHistory(quizHistory);
            } else {
                document.getElementById('quizHistoryList').innerHTML = 
                    '<div class="no-data">暂无答题记录</div>';
            }
        })
        .catch(error => {
            console.error('加载答题记录失败:', error);
            document.getElementById('quizHistoryList').innerHTML = 
                '<div class="no-data">加载失败，请刷新重试</div>';
        });
}

// 显示答题记录
function displayQuizHistory(history) {
    const container = document.getElementById('quizHistoryList');
    
    if (history.length === 0) {
        container.innerHTML = '<div class="no-data">暂无答题记录，快去答题吧！</div>';
        return;
    }
    
    container.innerHTML = history.map((quiz, index) => `
        <div class="quiz-item">
            <div class="quiz-header">
                <span class="quiz-category">${quiz.category_name}</span>
                <span class="quiz-time">${formatDateTime(quiz.created_at)}</span>
            </div>
            <div class="quiz-stats">
                <div class="quiz-stat">
                    <div class="quiz-stat-label">答对</div>
                    <div class="quiz-stat-value" style="color: #4caf50;">${quiz.correct_count}</div>
                </div>
                <div class="quiz-stat">
                    <div class="quiz-stat-label">答错</div>
                    <div class="quiz-stat-value" style="color: #ff4757;">${quiz.wrong_count}</div>
                </div>
                <div class="quiz-stat">
                    <div class="quiz-stat-label">得分</div>
                    <div class="quiz-stat-value" style="color: #667eea;">${quiz.score}</div>
                </div>
            </div>
            <div class="quiz-footer">
                ${quiz.time_elapsed ? `<span class="quiz-duration">用时: ${formatTime(quiz.time_elapsed)}</span>` : ''}
                <button class="btn-detail" onclick="showQuizDetail(${index})">查看详情</button>
            </div>
        </div>
    `).join('');
}

// 格式化日期时间
function formatDateTime(dateString) {
    const date = new Date(dateString);
    return date.toLocaleString('zh-CN');
}

// 格式化时间（秒）
function formatTime(seconds) {
    const minutes = Math.floor(seconds / 60);
    const secs = seconds % 60;
    return `${minutes}分${secs}秒`;
}

// 更新用户信息
function updateUserInfo() {
    const username = document.getElementById('updateUsername').value.trim();
    const email = document.getElementById('updateEmail').value.trim();
    
    // 清除错误信息
    document.getElementById('usernameError').textContent = '';
    document.getElementById('emailError').textContent = '';
    
    // 验证
    let hasError = false;
    
    if (!username) {
        document.getElementById('usernameError').textContent = '请输入用户名';
        hasError = true;
    }
    
    if (!email || !email.includes('@')) {
        document.getElementById('emailError').textContent = '请输入有效的邮箱';
        hasError = true;
    }
    
    if (hasError) return;
    
    // 发送请求
    fetch('/api/user/update-info', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ username, email })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showMessage('信息更新成功！', 'success');
            loadUserProfile(); // 重新加载
        } else {
            showMessage(data.message || '更新失败', 'error');
        }
    })
    .catch(error => {
        console.error('更新用户信息失败:', error);
        showMessage('网络错误，请稍后重试', 'error');
    });
}

// 修改密码
function updatePassword() {
    const oldPassword = document.getElementById('oldPassword').value;
    const newPassword = document.getElementById('newPassword').value;
    const confirmPassword = document.getElementById('confirmPassword').value;
    
    // 清除错误信息
    document.getElementById('oldPasswordError').textContent = '';
    document.getElementById('newPasswordError').textContent = '';
    document.getElementById('confirmPasswordError').textContent = '';
    
    // 验证
    let hasError = false;
    
    if (!oldPassword) {
        document.getElementById('oldPasswordError').textContent = '请输入当前密码';
        hasError = true;
    }
    
    if (!newPassword || newPassword.length < 6) {
        document.getElementById('newPasswordError').textContent = '新密码至少6位';
        hasError = true;
    }
    
    if (newPassword !== confirmPassword) {
        document.getElementById('confirmPasswordError').textContent = '两次密码不一致';
        hasError = true;
    }
    
    if (hasError) return;
    
    // 发送请求
    fetch('/api/user/update-password', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({ old_password: oldPassword, new_password: newPassword })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            showMessage('密码修改成功！', 'success');
            document.getElementById('updatePasswordForm').reset();
        } else {
            showMessage(data.message || '密码修改失败', 'error');
        }
    })
    .catch(error => {
        console.error('修改密码失败:', error);
        showMessage('网络错误，请稍后重试', 'error');
    });
}

// 显示消息
function showMessage(message, type = 'success') {
    const banner = document.getElementById('messageBanner');
    banner.textContent = message;
    banner.classList.add('show');
    
    if (type === 'error') {
        banner.classList.add('error');
    } else {
        banner.classList.remove('error');
    }
    
    setTimeout(() => {
        banner.classList.remove('show');
    }, 3000);
}

// 显示答题详情
function showQuizDetail(index) {
    const quiz = quizHistory[index];
    if (!quiz) return;
    
    // 填充详情数据
    document.getElementById('detailCategory').textContent = quiz.category_name;
    document.getElementById('detailTime').textContent = formatDateTime(quiz.created_at);
    document.getElementById('detailCorrect').textContent = quiz.correct_count;
    document.getElementById('detailWrong').textContent = quiz.wrong_count;
    document.getElementById('detailScore').textContent = quiz.score;
    
    // 计算统计数据
    const totalQuestions = quiz.correct_count + quiz.wrong_count;
    const accuracy = totalQuestions > 0 ? Math.round((quiz.correct_count / totalQuestions) * 100) : 0;
    const avgTime = quiz.time_elapsed && totalQuestions > 0 ? Math.round(quiz.time_elapsed / totalQuestions) : 0;
    
    document.getElementById('detailTotal').textContent = totalQuestions;
    document.getElementById('detailAccuracy').textContent = accuracy + '%';
    document.getElementById('detailDuration').textContent = formatTime(quiz.time_elapsed || 0);
    document.getElementById('detailAvgTime').textContent = avgTime + '秒';
    
    // 设置"再来一次"按钮
    const retryBtn = document.getElementById('retryQuizBtn');
    retryBtn.onclick = function() {
        window.location.href = '/quiz?category=' + encodeURIComponent(quiz.category_name);
    };
    
    // 加载详细答题记录
    loadQuizDetailAnswers(quiz.id);
    
    // 显示弹窗
    document.getElementById('quizDetailModal').style.display = 'flex';
}

// 加载答题详细记录
function loadQuizDetailAnswers(quizId) {
    const container = document.getElementById('questionsDetailList');
    container.innerHTML = '<div class="loading-text">正在加载答题详情...</div>';
    
    fetch(`/api/quiz/detail/${quizId}`)
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                displayQuizDetailAnswers(data.answers);
            } else {
                container.innerHTML = '<div class="no-data">暂无详细记录</div>';
            }
        })
        .catch(error => {
            console.error('加载答题详情失败:', error);
            container.innerHTML = '<div class="no-data">加载失败，请稍后重试</div>';
        });
}

// 显示答题详细记录
function displayQuizDetailAnswers(answers) {
    const container = document.getElementById('questionsDetailList');
    
    if (!answers || answers.length === 0) {
        container.innerHTML = '<div class="no-data">暂无详细记录</div>';
        return;
    }
    
    container.innerHTML = answers.map((answer, index) => {
        const isCorrect = answer.is_correct;
        const statusClass = isCorrect ? 'correct' : 'incorrect';
        const statusIcon = isCorrect ? '✓' : '✗';
        const statusText = isCorrect ? '正确' : '错误';
        
        // 生成选项HTML
        const options = ['A', 'B', 'C', 'D'];
        const optionsHtml = options.map(option => {
            if (!answer[`option_${option.toLowerCase()}`]) return '';
            
            let optionClass = 'question-option';
            if (option === answer.correct_answer) {
                optionClass += ' correct-option';
            }
            if (option === answer.user_answer && option !== answer.correct_answer) {
                optionClass += ' wrong-option';
            }
            if (option === answer.user_answer) {
                optionClass += ' user-selected';
            }
            
            return `
                <div class="${optionClass}">
                    <span class="option-label">${option}.</span>
                    <span class="option-text">${renderMarkdown(answer[`option_${option.toLowerCase()}`])}</span>
                </div>
            `;
        }).filter(html => html).join('');
        
        return `
            <div class="question-detail-item ${statusClass}">
                <div class="question-detail-header">
                    <span class="question-number">第 ${index + 1} 题</span>
                    <span class="question-status ${statusClass}">
                        ${statusIcon} ${statusText}
                    </span>
                </div>
                <div class="question-detail-body">
                    <div class="question-text">${renderMarkdown(answer.question_title)}</div>
                    <div class="question-options">
                        ${optionsHtml}
                    </div>
                    <div class="answer-info">
                        <div class="answer-item">
                            <span class="answer-label">你的答案：</span>
                            <span class="answer-value user-answer">${answer.user_answer || '未作答'}</span>
                        </div>
                        <div class="answer-item">
                            <span class="answer-label">正确答案：</span>
                            <span class="answer-value correct-answer">${answer.correct_answer}</span>
                        </div>
                    </div>
                    ${answer.explanation ? `
                        <div class="question-explanation">
                            <div class="explanation-title">💡 答案解析</div>
                            <div class="explanation-content">${renderMarkdown(answer.explanation)}</div>
                        </div>
                    ` : ''}
                </div>
            </div>
        `;
    }).join('');
    
    // 渲染数学公式
    setTimeout(() => {
        renderMath(container);
    }, 100);
}

// 关闭详情弹窗
function closeQuizDetail() {
    document.getElementById('quizDetailModal').style.display = 'none';
}

// 设置详情弹窗事件
function setupDetailModal() {
    // 详情弹窗关闭事件
    document.getElementById('closeModal').addEventListener('click', closeQuizDetail);
    document.getElementById('closeDetailBtn').addEventListener('click', closeQuizDetail);
    
    // 点击弹窗外部关闭
    window.addEventListener('click', function(event) {
        const modal = document.getElementById('quizDetailModal');
        if (event.target === modal) {
            closeQuizDetail();
        }
    });
}

// 加载用户信息
async function loadUserInfo() {
    try {
        const response = await fetch('/api/user/info');
        const data = await response.json();

        if (data.success && data.user) {
            displayUserInfo(data.user);
        } else {
            console.error('获取用户信息失败:', data.message);
        }
    } catch (error) {
        console.error('加载用户信息错误:', error);
    }
}

// 页面初始化
document.addEventListener('DOMContentLoaded', function() {
    // 加载用户信息
    loadUserInfo();
    
    // 设置头像上传功能
    setupAvatarUpload();
    
    // 设置标签页切换
    setupTabs();
    
    // 设置详情弹窗
    setupDetailModal();
    
    // 设置退出登录
    setupLogout();
    
    // 设置表单提交
    setupForms();
    
    // 加载答题历史
    loadQuizHistory();
});

// 设置标签页切换
function setupTabs() {
    const tabBtns = document.querySelectorAll('.tab-btn');
    const tabContents = document.querySelectorAll('.tab-content');

    tabBtns.forEach(btn => {
        btn.addEventListener('click', () => {
            const targetTab = btn.getAttribute('data-tab');

            // 移除所有活跃状态
            tabBtns.forEach(b => b.classList.remove('active'));
            tabContents.forEach(content => content.classList.remove('active'));

            // 添加活跃状态
            btn.classList.add('active');
            document.getElementById(targetTab + 'Tab').classList.add('active');

            // 如果切换到概览标签页，确保图表正确显示
            if (targetTab === 'overview') {
                setTimeout(() => {
                    // 确保canvas容器可见后再重绘图表
                    const quizCanvas = document.getElementById('quizTrendChart');
                    const subjectCanvas = document.getElementById('subjectChart');

                    if (quizCanvas && subjectCanvas) {
                        // 重置canvas尺寸
                        resetCanvasSize(quizCanvas);
                        resetCanvasSize(subjectCanvas);
                        updateCharts(); // 重新渲染图表
                    }
                }, 150);
            }
        });
    });
}

// 设置退出登录
function setupLogout() {
    const logoutBtn = document.getElementById('logoutBtn');
    if (logoutBtn) {
        logoutBtn.addEventListener('click', async () => {
            if (confirm('确定要退出登录吗？')) {
                try {
                    const response = await fetch('/logout', { method: 'POST' });
                    if (response.ok) {
                        window.location.href = '/login';
                    }
                } catch (error) {
                    console.error('退出登录失败:', error);
                }
            }
        });
    }
}

// 设置表单提交
function setupForms() {
    // 更新个人信息表单
    const updateInfoForm = document.getElementById('updateInfoForm');
    if (updateInfoForm) {
        updateInfoForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            // 这里可以添加更新个人信息的逻辑
        });
    }
    
    // 更新密码表单
    const updatePasswordForm = document.getElementById('updatePasswordForm');
    if (updatePasswordForm) {
        updatePasswordForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            // 这里可以添加更新密码的逻辑
        });
    }
}

// 加载答题历史
async function loadQuizHistory() {
    // 这里可以添加加载答题历史的逻辑
    const historyList = document.getElementById('quizHistoryList');
    if (historyList) {
        historyList.innerHTML = '<div class="no-data">暂无答题记录</div>';
    }
}

// 加载成就数据
async function loadAchievements() {
    try {
        const response = await fetch('/api/user/achievements');
        const data = await response.json();

        if (data.success) {
            displayAchievements(data.achievements);
            displayLevelInfo(data.level);
        } else {
            console.error('获取成就失败:', data.message);
        }
    } catch (error) {
        console.error('加载成就错误:', error);
    }
}

// 显示成就
function displayAchievements(achievements) {
    const unlockedList = document.getElementById('unlockedAchievements');
    const lockedList = document.getElementById('lockedAchievements');
    const countElement = document.getElementById('achievementCount');

    if (!unlockedList || !lockedList || !countElement) return;

    // 清空现有内容
    unlockedList.innerHTML = '';
    lockedList.innerHTML = '';

    // 显示已解锁成就
    if (achievements.unlocked.length > 0) {
        achievements.unlocked.forEach(achievement => {
            const achievementElement = createAchievementElement(achievement, true);
            unlockedList.appendChild(achievementElement);
        });
    } else {
        unlockedList.innerHTML = '<div class="no-data">暂无已解锁成就</div>';
    }

    // 显示未解锁成就
    if (achievements.locked.length > 0) {
        achievements.locked.forEach(achievement => {
            const achievementElement = createAchievementElement(achievement, false);
            lockedList.appendChild(achievementElement);
        });
    } else {
        lockedList.innerHTML = '<div class="no-data">暂无未解锁成就</div>';
    }

    // 更新成就统计
    countElement.textContent = `${achievements.unlocked.length}/${achievements.unlocked.length + achievements.locked.length}`;
}

// 创建成就元素
function createAchievementElement(achievement, isUnlocked) {
    const div = document.createElement('div');
    div.className = `achievement-item ${isUnlocked ? 'unlocked' : 'locked'}`;

    div.innerHTML = `
        <div class="achievement-icon">${achievement.icon}</div>
        <div class="achievement-info">
            <h4 class="achievement-name">${achievement.name}</h4>
            <p class="achievement-desc">${achievement.description}</p>
            ${isUnlocked ? `<small class="achievement-date">解锁时间: ${achievement.unlocked_at}</small>` : ''}
        </div>
        <div class="achievement-rarity ${achievement.rarity}">${achievement.rarity}</div>
    `;

    return div;
}

// 显示等级信息
function displayLevelInfo(level) {
    const levelElement = document.getElementById('userLevel');
    const expFillElement = document.getElementById('expFill');
    const expTextElement = document.getElementById('expText');

    if (levelElement) {
        levelElement.textContent = `Lv.${level.level}`;
    }

    if (expFillElement && expTextElement) {
        const currentExp = level.experience;
        const expForNextLevel = level.level * 100;
        const percentage = (currentExp / expForNextLevel) * 100;

        expFillElement.style.width = `${Math.min(percentage, 100)}%`;
        expTextElement.textContent = `${currentExp}/${expForNextLevel}`;
    }
}

// 加载学习目标
async function loadLearningGoals() {
    try {
        const response = await fetch('/api/user/learning-goals');
        const data = await response.json();

        if (data.success) {
            displayLearningGoals(data.goals);
        } else {
            console.error('获取学习目标失败:', data.message);
        }
    } catch (error) {
        console.error('加载学习目标错误:', error);
    }
}

// 显示学习目标
function displayLearningGoals(goals) {
    const goalsGrid = document.getElementById('goalsGrid');
    if (!goalsGrid) return;

    goals.forEach(goal => {
        const goalCard = goalsGrid.querySelector(`[data-goal-type="${goal.goal_type}"]`);
        if (goalCard) {
            const progressFill = goalCard.querySelector('.progress-fill');
            const progressText = goalCard.querySelector('.progress-text');

            if (progressFill && progressText) {
                // 这里应该根据实际进度计算，这里先显示示例
                const progress = Math.floor(Math.random() * 100); // 示例数据
                progressFill.style.width = `${progress}%`;
                progressText.textContent = `${progress}/${goal.target_quizzes}`;
            }
        }
    });
}

// 加载收藏夹
async function loadFavorites() {
    try {
        const response = await fetch('/api/user/favorites');
        const data = await response.json();

        if (data.success) {
            displayFavorites(data.favorites);
        } else {
            console.error('获取收藏夹失败:', data.message);
        }
    } catch (error) {
        console.error('加载收藏夹错误:', error);
    }
}

// 显示收藏夹
function displayFavorites(favorites) {
    const favoritesList = document.getElementById('favoritesList');
    if (!favoritesList) return;

    favoritesList.innerHTML = '';

    const questions = favorites.questions || [];
    const categories = favorites.categories || [];

    if (questions.length === 0 && categories.length === 0) {
        favoritesList.innerHTML = '<div class="no-data">暂无收藏内容</div>';
        return;
    }

    // 显示收藏的题目
    questions.forEach(item => {
        const itemElement = document.createElement('div');
        itemElement.className = 'favorite-item question-item';
        itemElement.innerHTML = `
            <div class="favorite-icon">📝</div>
            <div class="favorite-content">
                <h4>${item.title}</h4>
                <p>分类: ${item.category_name}</p>
            </div>
            <button class="btn-icon remove-favorite" onclick="removeFavorite('question', ${item.id})">🗑️</button>
        `;
        favoritesList.appendChild(itemElement);
    });

    // 显示收藏的分类
    categories.forEach(item => {
        const itemElement = document.createElement('div');
        itemElement.className = 'favorite-item category-item';
        itemElement.innerHTML = `
            <div class="favorite-icon">${item.icon}</div>
            <div class="favorite-content">
                <h4>${item.name}</h4>
                <p>${item.description}</p>
                <small>${item.question_count} 道题目</small>
            </div>
            <button class="btn-icon remove-favorite" onclick="removeFavorite('category', ${item.id})">🗑️</button>
        `;
        favoritesList.appendChild(itemElement);
    });
}

// 移除收藏
async function removeFavorite(itemType, itemId) {
    try {
        const response = await fetch(`/api/user/favorites/${itemType}/${itemId}`, {
            method: 'POST'
        });
        const data = await response.json();

        if (data.success) {
            showMessage('已从收藏中移除', 'success');
            loadFavorites(); // 重新加载收藏夹
        } else {
            showMessage(data.message || '操作失败', 'error');
        }
    } catch (error) {
        console.error('移除收藏错误:', error);
        showMessage('操作失败', 'error');
    }
}

// 图表实例存储
let quizTrendChart = null;
let subjectChart = null;

// 初始化图表
function initCharts() {
    // 销毁现有图表实例
    if (quizTrendChart) {
        quizTrendChart.destroy();
        quizTrendChart = null;
    }
    if (subjectChart) {
        subjectChart.destroy();
        subjectChart = null;
    }

    // 答题趋势图
    const quizTrendCtx = document.getElementById('quizTrendChart');
    if (quizTrendCtx) {
        // 重置canvas尺寸
        resetCanvasSize(quizTrendCtx);

        quizTrendChart = new Chart(quizTrendCtx, {
            type: 'line',
            data: {
                labels: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
                datasets: [{
                    label: '答题次数',
                    data: [12, 19, 3, 5, 2, 3, 9],
                    borderColor: '#4caf50',
                    backgroundColor: 'rgba(76, 175, 80, 0.1)',
                    tension: 0.4
                }]
            },
            options: {
                responsive: false, // 禁用响应式，避免尺寸变化
                maintainAspectRatio: true,
                scales: {
                    y: {
                        beginAtZero: true
                    }
                }
            }
        });
    }

    // 科目分布图
    const subjectCtx = document.getElementById('subjectChart');
    if (subjectCtx) {
        // 重置canvas尺寸
        resetCanvasSize(subjectCtx);

        subjectChart = new Chart(subjectCtx, {
            type: 'doughnut',
            data: {
                labels: ['综合知识', '科学技术', '文化艺术', '数学', '经济管理', 'IT技术'],
                datasets: [{
                    data: [30, 25, 15, 10, 10, 10],
                    backgroundColor: [
                        '#FF6384',
                        '#36A2EB',
                        '#FFCE56',
                        '#4BC0C0',
                        '#9966FF',
                        '#FF9F40'
                    ]
                }]
            },
            options: {
                responsive: false, // 禁用响应式，避免尺寸变化
                maintainAspectRatio: true
            }
        });
    }
}

// 更新图表数据
function updateCharts(realData = null) {
    if (realData) {
        // 如果有真实数据，更新图表
        if (quizTrendChart && realData.quizTrend) {
            quizTrendChart.data.labels = realData.quizTrend.labels;
            quizTrendChart.data.datasets[0].data = realData.quizTrend.data;
            quizTrendChart.update();
        }

        if (subjectChart && realData.subjectDistribution) {
            subjectChart.data.labels = realData.subjectDistribution.labels;
            subjectChart.data.datasets[0].data = realData.subjectDistribution.data;
            subjectChart.update();
        }
    } else {
        // 重新初始化图表（用于清理）
        initCharts();
    }
}

// 确保canvas尺寸正确的辅助函数
function resetCanvasSize(canvas) {
    if (canvas) {
        const container = canvas.parentElement;
        if (container) {
            const rect = container.getBoundingClientRect();
            const dpr = window.devicePixelRatio || 1;

            // 计算合适的尺寸（考虑padding和边框）
            const padding = 50; // 左右padding总和
            const availableWidth = rect.width - padding;
            const aspectRatio = 2; // 宽高比 2:1

            // 设置CSS尺寸
            canvas.style.width = availableWidth + 'px';
            canvas.style.height = (availableWidth / aspectRatio) + 'px';

            // 设置实际像素尺寸
            canvas.width = availableWidth * dpr;
            canvas.height = (availableWidth / aspectRatio) * dpr;

            // 缩放上下文以匹配设备像素比
            const ctx = canvas.getContext('2d');
            ctx.scale(dpr, dpr);
        }
    }
}

// 打开学习目标设置模态框
function openGoalModal(goalType) {
    const modal = document.getElementById('goalModal');
    const title = document.getElementById('goalModalTitle');
    const form = document.getElementById('goalForm');

    if (!modal || !title || !form) return;

    // 设置模态框标题
    const titles = {
        'daily': '设置每日目标',
        'weekly': '设置每周目标',
        'monthly': '设置每月目标'
    };
    title.textContent = titles[goalType] || '设置学习目标';

    // 设置表单的goal_type
    form.setAttribute('data-goal-type', goalType);

    // 显示模态框
    modal.style.display = 'flex';
}

// 关闭学习目标设置模态框
function closeGoalModal() {
    const modal = document.getElementById('goalModal');
    if (modal) {
        modal.style.display = 'none';
    }
}

// 加载偏好设置
async function loadPreferences() {
    try {
        const response = await fetch('/api/user/preferences');
        const data = await response.json();

        if (data.success) {
            displayPreferences(data.preferences);
        } else {
            console.error('获取偏好设置失败:', data.message);
        }
    } catch (error) {
        console.error('加载偏好设置错误:', error);
    }
}

// 显示偏好设置
function displayPreferences(preferences) {
    const themeSelect = document.getElementById('themeSelect');
    const notificationsEnabled = document.getElementById('notificationsEnabled');
    const reminderEnabled = document.getElementById('reminderEnabled');
    const reminderTime = document.getElementById('reminderTime');

    if (themeSelect) themeSelect.value = preferences.theme || 'light';
    if (notificationsEnabled) notificationsEnabled.checked = preferences.notifications_enabled;
    if (reminderEnabled) reminderEnabled.checked = preferences.reminder_enabled;
    if (reminderTime) reminderTime.value = preferences.reminder_time || '09:00';

    // 控制提醒时间的显示
    toggleReminderTime();
}

// 切换提醒时间显示
function toggleReminderTime() {
    const reminderEnabled = document.getElementById('reminderEnabled');
    const reminderTimeGroup = document.getElementById('reminderTimeGroup');

    if (reminderEnabled && reminderTimeGroup) {
        reminderTimeGroup.style.display = reminderEnabled.checked ? 'block' : 'none';
    }
}

// 页面初始化扩展
document.addEventListener('DOMContentLoaded', function() {
    // 现有的初始化代码...

    // 新增的功能初始化
    loadAchievements();
    loadLearningGoals();
    loadFavorites();
    loadPreferences();
    initCharts();

    // 设置学习目标模态框
    setupGoalModal();

    // 设置偏好设置
    setupPreferences();

    // 设置窗口大小改变时的图表重绘
    setupChartResize();
});

// 设置图表响应式重绘
function setupChartResize() {
    let resizeTimeout;

    window.addEventListener('resize', () => {
        clearTimeout(resizeTimeout);
        resizeTimeout = setTimeout(() => {
            // 检查当前是否在概览标签页
            const overviewTab = document.getElementById('overviewTab');
            if (overviewTab && overviewTab.classList.contains('active')) {
                const quizCanvas = document.getElementById('quizTrendChart');
                const subjectCanvas = document.getElementById('subjectChart');

                if (quizCanvas && subjectCanvas) {
                    // 重置canvas尺寸以适应新窗口大小
                    resetCanvasSize(quizCanvas);
                    resetCanvasSize(subjectCanvas);
                    updateCharts(); // 重新渲染图表
                }
            }
        }, 250); // 防抖延迟
    });

    // 页面卸载时清理图表实例
    window.addEventListener('beforeunload', () => {
        if (quizTrendChart) {
            quizTrendChart.destroy();
            quizTrendChart = null;
        }
        if (subjectChart) {
            subjectChart.destroy();
            subjectChart = null;
        }
    });
}

// 设置学习目标模态框
function setupGoalModal() {
    const modal = document.getElementById('goalModal');
    const closeBtn = document.getElementById('closeGoalModal');
    const form = document.getElementById('goalForm');

    if (closeBtn) {
        closeBtn.addEventListener('click', closeGoalModal);
    }

    if (modal) {
        modal.addEventListener('click', (e) => {
            if (e.target === modal) {
                closeGoalModal();
            }
        });
    }

    if (form) {
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            await saveLearningGoal();
        });
    }
}

// 保存学习目标
async function saveLearningGoal() {
    const form = document.getElementById('goalForm');
    const goalType = form.getAttribute('data-goal-type');

    const targetQuizzes = document.getElementById('targetQuizzes').value;
    const targetScore = document.getElementById('targetScore').value;
    const targetAccuracy = document.getElementById('targetAccuracy').value;

    try {
        const response = await fetch('/api/user/learning-goals', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                goal_type: goalType,
                target_quizzes: parseInt(targetQuizzes) || 0,
                target_score: parseInt(targetScore) || 0,
                target_accuracy: parseInt(targetAccuracy) || 0
            })
        });

        const data = await response.json();

        if (data.success) {
            showMessage('学习目标设置成功', 'success');
            closeGoalModal();
            loadLearningGoals(); // 重新加载目标
        } else {
            showMessage(data.message || '设置失败', 'error');
        }
    } catch (error) {
        console.error('保存学习目标错误:', error);
        showMessage('设置失败', 'error');
    }
}

// 设置偏好设置
function setupPreferences() {
    const reminderEnabled = document.getElementById('reminderEnabled');
    const preferencesForm = document.getElementById('preferencesForm');

    if (reminderEnabled) {
        reminderEnabled.addEventListener('change', toggleReminderTime);
    }

    if (preferencesForm) {
        preferencesForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            await savePreferences();
        });
    }
}

// 保存偏好设置
async function savePreferences() {
    const theme = document.getElementById('themeSelect').value;
    const notificationsEnabled = document.getElementById('notificationsEnabled').checked;
    const reminderEnabled = document.getElementById('reminderEnabled').checked;
    const reminderTime = document.getElementById('reminderTime').value;

    try {
        const response = await fetch('/api/user/preferences', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                theme: theme,
                notifications_enabled: notificationsEnabled,
                reminder_enabled: reminderEnabled,
                reminder_time: reminderTime
            })
        });

        const data = await response.json();

        if (data.success) {
            showMessage('偏好设置保存成功', 'success');
            // 应用主题
            applyTheme(theme);
        } else {
            showMessage(data.message || '保存失败', 'error');
        }
    } catch (error) {
        console.error('保存偏好设置错误:', error);
        showMessage('保存失败', 'error');
    }
}

// 应用主题
function applyTheme(theme) {
    document.documentElement.setAttribute('data-theme', theme);
}

